using Crux.Core.Websockets;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Builder;
/// <summary>
/// WebSocketApplicationBuilderExtensions
/// </summary>
public static class WebSocketApplicationBuilderExtensions
{
    /// <summary>
    ///
    /// </summary>
    public static IApplicationBuilder MapWebSocketHandle<THandler>(
        this IApplicationBuilder app,
        PathString path)
            where THandler : WebSocketHandler
    {
        return app.Map(path, (_app) =>
        {
            var provider = _app.ApplicationServices;

            var handler = provider.GetRequiredService<WebSocketConnectionHandler<THandler>>();
            var option = _app.ApplicationServices.GetRequiredService<IOptions<WebSocketOptions<THandler>>>();

            _app.UseMiddleware<WebSocketHandleMiddleware<THandler>>(handler, option);
        });
    }
}